/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.mybatis.table;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.jianggujin.dbfly.mybatis.JConfiguration;
import com.jianggujin.dbfly.mybatis.entity.JEntity;
import com.jianggujin.dbfly.mybatis.util.JElementBuilder;
import com.jianggujin.dbfly.mybatis.util.JProviderHelper;
import com.jianggujin.dbfly.util.JStringUtils;

/**
 * 动态表名生成器
 * 
 * @author jianggujin
 *
 */
public class JDynamicTableNameGenerator implements JTableNameGenerator {

    @Override
    public void generateTableName(JConfiguration configuration, Document document, Element parentElement,
            JEntity entity, String parameterName) {
        if (JDynamicTableName.class.isAssignableFrom(entity.getEntityClass())) {
            String prefix = JProviderHelper.getParameterPrefix(parameterName);
            Element chooseElement = JElementBuilder.buildChooseElement(document);
            Element whenElement = JElementBuilder.buildWhenElement(document,
                    JStringUtils.format(
                            "@{}@isDynamicParameter({}) and {}dynamicTableName != null and {}dynamicTableName != ''",
                            JDynamicTableNameGenerator.class.getCanonicalName(), parameterName, prefix, prefix));
            JElementBuilder.appendChild(document, whenElement, JStringUtils.format("${{}dynamicTableName}", prefix));
            chooseElement.appendChild(whenElement);
            Element otherwiseElement = JElementBuilder.buildOtherwiseElement(document);
            JElementBuilder.appendChild(document, otherwiseElement, entity.getFullTableName());
            chooseElement.appendChild(otherwiseElement);
            parentElement.appendChild(chooseElement);
        } else {
            JElementBuilder.appendChild(document, parentElement, entity.getFullTableName());
        }
    }

    /**
     * 判断参数是否支持动态表名
     *
     * @param parameter
     * @return true支持，false不支持
     */
    public static boolean isDynamicParameter(Object parameter) {
        if (parameter != null && parameter instanceof JDynamicTableName) {
            return true;
        }
        return false;
    }
}
